#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author: Wild Orange
# @Email: jixuanfan_seu@163.com
# @Date:   2020-06-21 16:06:14
# @Last Modified time: 2020-07-23 22:01:30

import requests
AK='[这里填写自己申请的AK值]'

def Pos2Coord(name):
	'''
		@func: 通过百度地图API将地理名称转换成经纬度
		@note: 官方文档 http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding
		@output:
			lng: 经度
			lat: 纬度
			conf: 打点绝对精度（即坐标点的误差范围）
			comp: 描述地址理解程度。分值范围0-100，分值越大，服务对地址理解程度越高
			level: 能精确理解的地址类型
	'''
	url = 'http://api.map.baidu.com/geocoding/v3/?address=%s&output=json&ak=%s'%(name,AK)
	res = requests.get(url)
	if res.status_code==200:
		val=res.json()
		if val['status']==0:
			retVal={'lng':val['result']['location']['lng'],'lat':val['result']['location']['lat'],\
			'conf':val['result']['confidence'],'comp':val['result']['comprehension'],'level':val['result']['level']}
		else:
			retVal=None
		return retVal
	else:
		print('无法获取%s经纬度'%name)

def Coord2Pos(lng,lat,town='true'):
	'''
		@func: 通过百度地图API将经纬度转换成地理名称
		@input:
			lng: 经度
			lat: 纬度
			town: 是否获取乡镇级地理位置信息，默认获取。可选参数（true/false）
		@output:
			address:解析后的地理位置名称
			province:省份名称
			city:城市名
			district:县级行政区划名
			town: 乡镇级行政区划
			adcode: 县级行政区划编码
			town_code: 镇级行政区划编码
	'''
	url='http://api.map.baidu.com/reverse_geocoding/v3/?output=json&ak=%s&location=%s,%s&extensions_town=%s'%(AK,lat,lng,town)
	res=requests.get(url)
	if res.status_code==200:
		val=res.json()
		if val['status']==0:
			val=val['result']
			retVal={'address':val['formatted_address'],'province':val['addressComponent']['province'],\
			'city':val['addressComponent']['city'],'district':val['addressComponent']['district'],\
			'town':val['addressComponent']['town'],'adcode':val['addressComponent']['adcode'],
			'town_code':val['addressComponent']['town_code']}
		else:
			retVal=None
		return retVal
	else:
		print('无法获取(%s,%s)的地理信息！'%(lat,lng))

def License():
	S='87/101/108/99/111/109/101/32/116/111/32/117/115/101/32/116/104/105/115/32/112/114/111/103/\
	114/97/109/33/10/65/117/116/104/111/114/58/32/68/101/99/111/100/101/10/72/111/109/101/112/97/\
	103/101/58/32/71/105/116/101/101/40/104/116/116/112/115/58/47/47/103/105/116/101/101/46/99/111/\
	109/47/106/105/120/117/97/110/102/97/110/41/10/32/32/32/32/32/32/32/32/32/32/67/83/68/78/40/104/\
	116/116/112/115/58/47/47/98/108/111/103/46/99/115/100/110/46/110/101/116/47/113/113/95/51/53/52/\
	48/56/48/51/48/41/10'
	print(''.join([chr(int(x)) for x in S.split('/')]))
License()

if __name__ == '__main__':
	Pos2Coord('江苏省南京市江宁区')
	Coord2Pos(118.81871976794395,31.88198449339288)